<!-- 日报 -->
<template>
  <div class="timelog">
    <div class="timelog-container">
      <div class="team" v-if="isShow">
        <UserCell :userList="userList" @clicked="handleClickedUser" />
      </div>
      <div class="calendar">
        <div class="calendar-warp">
          <el-calendar v-model="valueCalendar">
            <template #date-cell="{ data }">
              <CalendarCell :date="data.date" :timelog-list="timelogList" />
            </template>
          </el-calendar>
        </div>
        <div ref="timelogTableContainer" class="timelog-table-container">
          <el-scrollbar :height="tableHeight">
            <TodayInfomation v-if="todayInfo" v-bind="todayInfo" />
          </el-scrollbar>
        </div>
      </div>
      <div class="content">
        <div class="btn-group">
          <div class="tt">{{ utils.formatDate(selectedDate, 'yyyy-MM-dd') }}</div>
          <div class="btn-cells">
            <el-button v-if="false" type="primary" :disabled="!flagContent" :icon="Plus" @click="handleClickBtnOpenDialog">新增日报</el-button>
            <el-button type="danger" :disabled="!flagContent" :icon="Delete" @click="handleClickBtnDeleteAllTimelog">清空</el-button>
          </div>
        </div>
        <div class="content-bd">
          <div v-if="flagContent" class="content-bd-timeline">
            <TimeSlider ref="timeSlider" :time-dates="timeDates" :today="todayInfo.date" :timelogCategory="projectTypes" :begin-time="beginTime" :end-time="endTime" :disabled-times="disabledTimes" :logList="timelineList" @checked="handleCheckedTimeSlider" @delete-cell="handleDeleteCellTimeSlider" />
          </div>
          <div v-else>当前日期不可用</div>
        </div>
      </div>
    </div>
  </div>
  <DialogAddTimelog ref="dialogAddTimelog" :project-types="projectTypes" :tilelogDate="selectedDate" :occupiedTimeSlots="occupiedTimeSlots" @submited="handleSubmited" @closed="handlerClosed" />
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import DialogAddTimelog from '../components/dialog/DialogAddTimelog.vue'
// import { getAll } from '../api/Users'
import UserCell from '../components/Timelog/UserCell.vue'
import TimeSlider from '../components/Timelog/TimeSliderCopy.vue'
import TodayInfomation from '../components/Timelog/TodayInfomation.vue'
import * as utils from '../utils'
import IUser from '../interface/IUsers'
import { useUsersStore, useTaskTypeStore } from '../stores'
import IProjectTypes from '../interface/IProjectTypes'
import { ElMessage, ElMessageBox } from 'element-plus'
import CalendarCell from '../components/Timelog/CalendarCell.vue'
import http from '../http'
import eventBus from '../eventBus'

const usersStore = useUsersStore()
const dialogAddTimelog = ref()
const timeSlider = ref()
const valueCalendar = ref(new Date())
const userList = ref([])
const timelogList = ref()
const timelogFullData = ref()
const timelineList = ref([])
const todayInfo = ref<any>({ data: '' })
const flagContent = ref(false)
const isShow = ref(false)
const projectTypes = ref<IProjectTypes[]>(useTaskTypeStore().getAllState())
const selectedDate = ref(new Date())
// 已占用的时间段
const occupiedTimeSlots = ref<any[]>([])
const timelogTableContainer = ref<HTMLElement | null>(null)
const tableHeight = ref(200)

const timeDates = ref<any[]>(['08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00'])
const disabledTimes = ref<any[]>(['08:00', '09:00', '13:00', '16:00'])
const beginTime = ref('08:00')
const endTime = ref('16:50')

const handleCheckedTimeSlider = (items: any) => {
  // console.log('handleCheckedTimeSlider', items)
  handleClickBtnOpenDialog(items)
}
watch(
  () => valueCalendar.value,
  async (newValue) => {
    await getTimelog()
    nextTick(async () => {
      await checkDay(newValue)
    })
  }
)
/**
 * 将记录数组转换为日期与百分比的映射对象
 *
 * 此函数接收一个记录数组，每个记录包含一个日期和对应的百分比
 * 它将这些记录转换为一个对象，其中日期为键，百分比为值
 * 这样可以在O(1)时间复杂度内快速访问特定日期的百分比
 *
 * @param records 记录数组，每个元素包含日期和百分比信息
 * @returns 一个对象，键为日期，值为对应的百分比
 */
function convertListToObject(records: []): Record<string, number> {
  // console.log('records', records)
  // 初始化一个空对象来存储日期与百分比的映射
  const result: Record<string, any> = {}

  // 遍历记录数组
  records.forEach((record: any) => {
    const date = record.timelogDate
    const duration = record.durationTime
    // 将记录的日期作为键，百分比作为值，存储到结果对象中
    if (result[date]) {
      result[date] += duration
    } else {
      result[date] = duration
    }
  })

  // console.log('result', result)
  // for (const key in result) {
  //   const percentage = (result[key] / 400) * 100
  //   result[key] = percentage
  // }
  return result
}
/**
 * 设置时间线和今日信息
 *
 * @param val 日期对象
 */
function setTimelineAndTodayInfo(val: Date) {
  const date = utils.formatDate(val, 'yyyy-MM-dd')
  const item = timelogFullData.value.filter((item: any) => {
    return item.timelogDate === date
  })
  nextTick(() => {
    timelineList.value = item || []
  })
  // console.log('date 2', date)
  // console.log('！===== timelineList.value', timelineList.value)

  const { startWorkTime, endWorkTime, startLunchTime, endLunchTime } = usersStore.getAllState() as any
  // console.log('{ startWorkTime, endWorkTime, startLunchTime, endLunchTime }', { startWorkTime, endWorkTime, startLunchTime, endLunchTime })
  todayInfo.value = {
    date,
    startWorkTime,
    endWorkTime,
    startLunchTime,
    endLunchTime,
  }
  beginTime.value = startWorkTime
  endTime.value = endWorkTime
}

/**
 * 获取时间日志列表
 *
 * @returns Promise<void>
 */
const getTimelog = async () => {
  const [start, end] = getMonthStartAndEnd(valueCalendar.value)
  const res = await http({
    path: '/dev-api/oa/timelog/list',
    method: 'GET',
    params: {
      userName: usersStore.user.username,
      pageSize: 99999,
      startTimelogDate: utils.formatDate(start, 'yyyy-MM-dd'),
      endTimelogDate: utils.formatDate(end, 'yyyy-MM-dd'),
    },
  })
  timelogFullData.value = res.rows
  timelogList.value = convertListToObject(res.rows)
  // console.log('timelog', res)
  // console.log('timelogList.value', timelogList.value)
}

/**
 * 获取当月的第一天和最后一天
 *
 * @returns 返回包含两个Date对象的数组，第一个为当月第一天，第二个为当月最后一天
 */
const getMonthStartAndEnd = (now: Date = new Date()) => {
  // 获取当前日期
  const currentYear = now.getFullYear()
  const currentMonth = now.getMonth() // 注意：JavaScript中月份是从0开始的，即0代表1月

  // 设置当月的第一天
  const firstDayOfMonth = new Date(currentYear, currentMonth, 1)

  // 获取当月的最后一天日期（下一个月的第一天减去1天）
  const lastDayOfMonth = new Date(currentYear, currentMonth + 1, 0)

  // 返回包含第一天和最后一天Date对象的数组
  return [firstDayOfMonth, lastDayOfMonth]
}

/**
 * 获取用户列表
 *
 * @returns 无返回值
 */
const getUserList = async () => {
  // const req = await getAll()
  // userList.value = req.data
  // userList.value.forEach((item: any, index: number) => {
  //   item.active = index === 0
  // })
}
const handleWindowResized = () => {
  // nextTick(async () => {
  if (timelogTableContainer.value) {
    tableHeight.value = timelogTableContainer.value.offsetHeight // 计算并设置高度
    // console.log('handleWindowResized', tableHeight.value)
  }
  // })
}
eventBus.on('windowResized', handleWindowResized)

onMounted(async () => {
  await getUserList()
  // await getProjectType()
  await getTimelog()
  flagContent.value = true
  nextTick(async () => {
    await checkDay(new Date())
    handleWindowResized()
  })

  // nextTick(() => {
  //   setTimelineAndTodayInfo(valueCalendar.value)
  // })
  const temp = usersStore.getAllState() as IUser
  // console.log('IUser', temp)
  if (temp && temp.role) {
    isShow.value = temp.role < 5
  }
})

onUnmounted(() => {
  eventBus.off('windowResized', handleWindowResized)
})
const handleClickedUser = (useritem: any) => {
  userList.value.map((item: any) => {
    item.active = item.id === useritem.id
  })
}
/**
 * 检查日期
 *
 * @param day 日期对象
 * @returns 无返回值
 */
const checkDay = (day: Date) => {
  // console.log('day', day)
  const date = utils.formatDate(day, 'yyyy-MM-dd')
  selectedDate.value = day
  setTimelineAndTodayInfo(day)
  // const [firstDay, currentDay] = getMonthDates()
  const [today, twoWeeksAgo] = utils.getTodayAndPreviousTwoWeeks(new Date())

  // 不限定时间 可用时间段
  flagContent.value = utils.isDateBetween(utils.formatDate(twoWeeksAgo, 'yyyy-MM-dd'), utils.formatDate(today, 'yyyy-MM-dd'), date)
  flagContent.value = true
  // console.log('firstDay', firstDay)
  // console.log('currentDay', currentDay)
  // console.log('today', utils.formatDate(today, 'yyyy-MM-dd'))
  // console.log('twoWeeksAgo', utils.formatDate(twoWeeksAgo, 'yyyy-MM-dd'))

  // 检查 当前日期 可用时间段
  occupiedTimeSlots.value = timelineList.value.map((item: any) => `${item.startTime.split(' ')[1]} - ${item.endTime.split(' ')[1]}`)
  // console.log('result', result)
  // occupiedTimeSlots.value
}

/**
 * 点击按钮打开对话框
 *
 * @param item 要传入的参数
 */
const handleClickBtnOpenDialog = (item: any) => {
  const workTime: any[] = []
  timelineList.value.forEach((e: any) => {
    // workTime.push(`${e.startTime.slice(-5)} - ${e.endTime.slice(-5)}`)
    workTime.push([new Date(e.startTime), new Date(e.endTime)])
  })
  // console.log('点击按钮打开对话框 item', [item[0].value, item[1].value], workTime)

  dialogAddTimelog.value?.openDialog([item[0].value, item[1].value], workTime)
}

/**
 * 处理表单提交
 *
 * @async
 */
const handleSubmited = async () => {
  setTimeout(async () => {
    await getTimelog()
    nextTick(() => {
      checkDay(new Date(selectedDate.value))
    })
  }, 1000)
}

const handlerClosed = () => {
  timeSlider.value?.clearSelectedCell()
}

// }
const deleteTimelogByIds = async (ids: string) => {
  const res = await http({
    method: 'DELETE',
    path: '/dev-api/oa/timelog/' + ids,
    params: {},
  })
  const { code } = res
  if (code === 200) {
    await getTimelog()
    // console.log('Delete', code)
    nextTick(() => {
      checkDay(new Date(selectedDate.value))
    })
  }
}
const handleClickBtnDeleteAllTimelog = () => {
  const doDay = utils.formatDate(selectedDate.value, 'yyyy-MM-dd')
  ElMessageBox.confirm(`确定清空 ${doDay} 所有日报吗？`, '提示')
    .then(async () => {
      // 确认删除
      const ids = timelineList.value.map((item: any) => item.id)
      await deleteTimelogByIds(ids.join(','))
      ElMessage({
        type: 'success',
        message: `成功删除 ${ids.length} 条记录！`,
      })
    })
    .catch(() => {})
}

const handleDeleteCellTimeSlider = (ids: any[], type: string = 'all') => {
  const doDay = utils.formatDate(selectedDate.value, 'yyyy-MM-dd')
  let msg = `确定删除 ${doDay} 所有日报吗？`
  if (type !== 'all') {
    msg = `确定删除记录吗？`
  }

  ElMessageBox.confirm(msg, '提示')
    .then(async () => {
      // 确认删除
      await deleteTimelogByIds(ids.join(','))
      ElMessage({
        type: 'success',
        message: `成功删除 ${ids.length} 条记录！`,
      })
    })
    .catch(() => {})
}
</script>
<style lang="scss" scoped>
.timelog {
  height: 100%;
  .timelog-container {
    height: 100%;
    display: flex;
    .team {
      display: flex;
      flex-direction: column;
      padding-right: 20px;
    }
    .calendar {
      flex: 3;
      border: 1px solid #ebeef5;
      border-right: 0;
      display: flex;
      flex-direction: column;
      height: 100%;
      overflow: hidden;
      .calendar-warp {
        overflow: hidden;
        flex: 1;

        .day {
          font-size: 20px;
          font-weight: bold;
        }
        .cell {
          height: 100%;
          margin: -8px;
          height: calc(100% + 16px);
          padding: 8px;
          &.brand {
            background-color: #c6e2ff;
          }
          &.success {
            background-color: #d1edc4;
          }
          &.warning {
            background-color: #f8e3c5;
          }
          &.danger {
            background-color: #fcd3d3;
          }
          &.info {
            // background-color: #dedfe0;
          }
        }
      }
      .mm {
        display: none;
      }
      .timelog-table-container {
        // max-height: 340px;
        // min-height: 140px;
        padding: 0 20px;
        height: 336px;
      }
    }
    .content {
      flex: 2;
      border: 1px solid #ebeef5;
      border-left: 0;
      border-right: 0;
      display: flex;
      flex-direction: column;
      .btn-group {
        padding: 9px 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #ebeef5;
        margin-bottom: 20px;
        .tt {
          flex: 1;
          text-align: center;
        }
        .btn-group {
        }
      }
      .content-bd {
        flex: 1;
        position: relative;
        .content-bd-timeline {
          overflow: auto;
          height: calc(100% - 20px);
          position: absolute;
          padding-right: 10px;
          width: 100%;
        }
      }
    }
  }
}
</style>
